package com.vip.jwt.common.utils.baidu;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.FileUtil;
import com.vip.jwt.common.utils.RedisUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 百度语音技术工具类
 */
public class BaiduAudioUtil {

    @Getter
    private static String API_KEY;

    @Getter
    private static String SECRET_KEY;

    @Value("${baidu-audio-apikey}")
    public void setApiKey(String apiKey) {
        API_KEY = apiKey;
    }

    @Value("${baidu-audio-secretkey}")
    public void setSecretKey(String secretKey) {
        SECRET_KEY = secretKey;
    }

    /**
     * 获取AccessToken
     * @return
     */
    public static String accessToken()
    {
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        Map<String,Object> params = new HashMap<>(16);
        params.put("grant_type","client_credentials");
        params.put("client_id",API_KEY);
        params.put("client_secret",SECRET_KEY);
        return HttpRequest.get(url).form(params).execute().body();
    }

    /**
     * 将百度AccessToken存入Redis
     * @return
     */
    public static String getAccessToken(){
        String key = "baidu_audio_access_token";
        // 首先验证Redis有没有accessToken
        Boolean bo = RedisUtil.hasKey(key);
        String accessTokenStr;
        if(bo){
            accessTokenStr = RedisUtil.get(key);
        }else{
            String jsonStr = accessToken();
            JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
            if(null!=jsonObject.get("error")){
                String error = jsonObject.get("error").toString();
                if("invalid_request".equals(error)){
                    throw new MyException(jsonObject.get("error_description").toString());
                }
            }
            accessTokenStr = jsonObject.get("access_token").toString();
            RedisUtil.set(key,accessTokenStr);
            int expires_in = Integer.parseInt(jsonObject.get("expires_in").toString());
            RedisUtil.expire(key,expires_in, TimeUnit.SECONDS);
        }
        return accessTokenStr;
    }

    /**
     * 语音转文本
     * @return
     */
    public static String audioToText(String accessToken,String audioBase64,Long len){
        String url = "http://vop.baidu.com/server_api";
        Map<String,Object> params = new HashMap<>(16);
        params.put("format","m4a");
        params.put("rate",16000);
        params.put("channel",1);
        params.put("cuid","feawg45aw4g7ew5g54a8g74eawg548");
        params.put("token",accessToken);
        params.put("speech",audioBase64);
        params.put("len",len);
        String jsonStr = new JSONObject(params).toString();
        return HttpRequest.post(url).header("Content-Type","application/json")
                .header("Content-Type","audio/m4a;rate=16000")
                .body(jsonStr).execute().body();
    }

}
